﻿using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;

namespace Hotfix
{
    /// <summary>
    /// 
    /// </summary>
    public class XHotfixAssetBundleAssetInfo
    {
        /// <summary>
        /// 
        /// </summary>
        public bool isScene 
        { get; set; }
        
        /// <summary>
        /// 
        /// </summary>
        public bool isFolder
        { get; set; }
        
        /// <summary>
        /// 
        /// </summary>
        public long fileSize;

        /// <summary>
        /// 
        /// </summary>
        private HashSet<string> parents;

        /// <summary>
        /// 
        /// </summary>
        private string assetName;

        /// <summary>
        /// 
        /// </summary>
        public string assetDisplayName;
        /// <summary>
        /// 
        /// </summary>
        private string assetBundleName;

        /// <summary>
        /// 
        /// </summary>
        private XHotfixMessageSystem.MessageState assetMessages = new XHotfixMessageSystem.MessageState();

        /// <summary>
        /// 
        /// </summary>
        private List<XHotfixAssetBundleAssetInfo> dependencies = null;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="inName"></param>
        /// <param name="bundleName"></param>
        public XHotfixAssetBundleAssetInfo(string inName, string bundleName="")
        {
            fullAssetName = inName;
            assetBundleName = bundleName;
            parents = new HashSet<string>();
            isScene = false;
            isFolder = false;
        }

        /// <summary>
        /// 
        /// </summary>
        public string fullAssetName
        {
            get { return assetName; }
            set
            {
                assetName = value;
                assetDisplayName = System.IO.Path.GetFileNameWithoutExtension(assetName);

                System.IO.FileInfo fileInfo = new System.IO.FileInfo(assetName);
                if (fileInfo.Exists)
                    fileSize = fileInfo.Length;
                else
                    fileSize = 0;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string displayName
        {
            get { return assetDisplayName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string bundleName
        { 
            get { return System.String.IsNullOrEmpty(assetBundleName) ? "auto" : assetBundleName; } 
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public Color GetColor()
        {
            if (System.String.IsNullOrEmpty(assetBundleName))
                return XHotfixAssetBundleModel.COLOR_LIGHT_GREY;
            else
                return Color.white;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="flag"></param>
        /// <returns></returns>
        public bool IsMessageSet(XHotfixMessageSystem.MessageFlag flag)
        {
            return assetMessages.IsSet(flag);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="on"></param>
        public void SetMessageFlag(XHotfixMessageSystem.MessageFlag flag, bool on)
        {
            assetMessages.SetFlag(flag, on);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public MessageType HighestMessageLevel()
        {
            return assetMessages.HighestMessageLevel();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IEnumerable<XHotfixMessageSystem.Message> GetMessages()
        {
            List<XHotfixMessageSystem.Message> messages = new List<XHotfixMessageSystem.Message>();
            if(IsMessageSet(XHotfixMessageSystem.MessageFlag.SceneBundleConflict))
            {
                var message = displayName + "\n";
                if (isScene)
                    message += "Is a scene that is in a bundle with non-scene assets. Scene bundles must have only one or more scene assets.";
                else
                    message += "Is included in a bundle with a scene. Scene bundles must have only one or more scene assets.";

                messages.Add(new XHotfixMessageSystem.Message(message, MessageType.Error));
            }

            if(IsMessageSet(XHotfixMessageSystem.MessageFlag.DependencySceneConflict))
            {
                var message = displayName + "\n";
                message += XHotfixMessageSystem.GetMessage(XHotfixMessageSystem.MessageFlag.DependencySceneConflict).message;
                
                messages.Add(new XHotfixMessageSystem.Message(message, MessageType.Error));
            }

            if (IsMessageSet(XHotfixMessageSystem.MessageFlag.AssetsDuplicatedInMultBundles))
            {
                var bundleNames = XHotfixAssetBundleModel.CheckDependencyTracker(this);
                string message = displayName + "\n" + "Is auto-included in multiple bundles:\n";

                foreach(var bundleName in bundleNames)
                {
                    message += bundleName + ", ";
                }

                //remove trailing comma.
                message = message.Substring(0, message.Length - 2);
                messages.Add(new XHotfixMessageSystem.Message(message, MessageType.Warning));
            }

            if (System.String.IsNullOrEmpty(assetBundleName) && parents.Count > 0)
            {
                //refine the parent list to only include those in the current asset list
                var message = displayName + "\n" + "Is auto included in bundle(s) due to parent(s): \n";
                foreach (var parent in parents)
                {
                    message += parent + ", ";
                }

                //remove trailing comma.
                message = message.Substring(0, message.Length - 2);
                messages.Add(new XHotfixMessageSystem.Message(message, MessageType.Info));
            }            

            if (dependencies != null && dependencies.Count > 0)
            {
                var message = string.Empty;
                var sortedDependencies = dependencies.OrderBy(d => d.bundleName);
                foreach (var dependent in sortedDependencies)
                {
                    if (dependent.bundleName != bundleName)
                    {
                        message += dependent.bundleName + " : " + dependent.displayName + "\n";
                    }
                }
                if (string.IsNullOrEmpty(message) == false)
                {
                    message = message.Insert(0, displayName + "\n" + "Is dependent on other bundle's asset(s) or auto included asset(s): \n");
                    message = message.Substring(0, message.Length - 1);//remove trailing line break.
                    messages.Add(new XHotfixMessageSystem.Message(message, MessageType.Info));
                }
            }            

            messages.Add(new XHotfixMessageSystem.Message(displayName + "\n" + "Path: " + fullAssetName, MessageType.Info));

            return messages;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        public void AddParent(string name)
        {
            parents.Add(name);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        public void RemoveParent(string name)
        {
            parents.Remove(name);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string GetSizeString()
        {
            if (fileSize == 0)
                return "--";

            return EditorUtility.FormatBytes(fileSize);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public List<XHotfixAssetBundleAssetInfo> GetDependencies()
        {
            //not sure this refreshes enough. need to build tests around that.
            if (dependencies == null)
            {
                dependencies = new List<XHotfixAssetBundleAssetInfo>();
                if (AssetDatabase.IsValidFolder(assetName))
                {
                    //if we have a folder, its dependencies were already pulled in through alternate means.  no need to GatherFoldersAndFiles
                    //GatherFoldersAndFiles();
                }
                else
                {
                    string[] depends = AssetDatabase.GetDependencies(assetName, true);
                    foreach (var dep in depends)
                    {
                        if (dep != assetName)
                        {
                            var asset = XHotfixAssetBundleModel.CreateAsset(dep, this);
                            if (asset != null)
                                dependencies.Add(asset);
                        }
                    }
                }
            }

            return dependencies;
        }
    }
}
